package com.syni.mdd.sjb.community.base.utils;

import com.alibaba.fastjson.JSON;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.syni.mdd.sjb.common.component.utils.common.constants.CommonResultCode;
import com.syni.mdd.sjb.common.component.utils.common.utils.RpcResponseVo;
import com.syni.mdd.sjb.common.component.utils.common.utils.StringUtils;
import com.syni.mdd.sjb.common.component.utils.common.utils.WebUtils;
import com.syni.mdd.sjb.common.component.utils.feign.service.mdd.commonuser.UserRestService;
import com.syni.mdd.sjb.community.base.entity.bo.UserData;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

@Component
@Log4j2
public class TokenUtils {

    @Autowired
    UserRestService userRestService;

    public Integer checkUser(String token){
        try {
            RpcResponseVo rpcResponseVo = userRestService.checkZuulIntoUser(token);
            if(rpcResponseVo.getStatus().equals(CommonResultCode.CODE_NORMAL)){
                Map<String,Object> data = (Map<String, Object>) rpcResponseVo.getData();
                if(data.containsKey("userid") && StringUtils.checkNullAndEmpty(data.get("userid"))) {
                    return Integer.parseInt(data.get("userid").toString());
                }
            }
        }catch (Exception e){
            log.error("checkUser error:",e);
        }
        return null;
    }

    public static UserData checkH5UserToken(String token){
        UserData userData = null;
        try {
            List<String> tokenData = JWT.decode(token).getAudience();
            if(!(tokenData.size() > 0)) {
                return userData;
            }
            String userDataJson = tokenData.get(0);
            userData = JSON.parseObject(userDataJson, UserData.class);
            JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(WebUtils.MD5(userData.getCorpId() + userData.getUserId()))).build();
            jwtVerifier.verify(token);
        }catch (Exception e){
            log.error(e.getMessage(),e);
            userData = null;
        }
        return userData;
    }
}
